<template>
  <div class="wrap">
    <div
      v-for="(_, key) in tabs"
      class="item"
      :class="{ active: tab === key }"
      @click="tab = key"
      :key="key"
    >
      {{ displayName(key) }}
    </div>
    <div class="code" :class="{ active: showCode }" @click="showCode = showCode == '0' ? '1' : '0'">
      code
    </div>
  </div>
  <component v-if="tabs[tab]" :is="defineAsyncComponent(tabs[tab])" />
  <Teleport to="body">
    <Transition>
      <div class="prism" v-if="showCode == '1' && text">
        <Prism language="javascript">{{ text }}</Prism>
      </div>
    </Transition>
  </Teleport>
</template>
<script setup>
import Prism from 'vue-prism-component'
import 'prismjs/themes/prism.css'
import 'prismjs/components/prism-javascript'

import { defineAsyncComponent, watch, ref } from 'vue'
const modules = import.meta.glob('@/**/*.vue', { query: '?raw', import: 'default' })

const props = defineProps({
  tabs: { type: Object, default: () => ({}) },
})
const showCode = ref(localStorage.getItem('showCode'))
watch(showCode, () => {
  localStorage.setItem('showCode', showCode.value)
})
const tab = defineModel()
const text = ref()
watch(tab, async (v) => {
  text.value = await modules[v]()
})
watch(
  () => props.tabs,
  () => {
    if (!props.tabs[tab.value]) {
      tab.value = Object.keys(props.tabs)[0]
    }
  },
  { immediate: true },
)
const displayName = (key) => {
  return key.substring(key.lastIndexOf('/') + 1, key.lastIndexOf('.'))
}
</script>
<style lang="scss" scoped>
.wrap {
  position: relative;
  display: flex;
  gap: 8px;
  height: 28px;
  line-height: 28px;
  border-bottom: 1px solid var(--border-color);
}
.item {
  cursor: pointer;
  &.active {
    color: var(--primary-color);
  }
}
.code {
  position: absolute;
  right: 0;
  height: 100%;
  padding: 0 4px;
  display: flex;
  align-items: center;
  cursor: pointer;
  &.active {
    color: var(--primary-color);
  }
}
.prism {
  position: fixed;
  right: 0;
  left: 0;
  bottom: 0;
  max-height: 50%;
  overflow-y: auto;

  .language-javascript {
    margin: 0;
  }
}

.v-enter-active,
.v-leave-active {
  transition: all 0.25s ease;
}

.v-leave-from,
.v-enter-to {
  transform: translateY(0);
}
.v-leave-to,
.v-enter-from {
  transform: translateY(100%);
}
</style>
